package main

import (
	"fmt"
	v1http "gitee.com/scottq/go-framework/src/v1/httpserver"
	v1log "gitee.com/scottq/go-framework/src/v1/log"
	"os"
	"path/filepath"
	"time"
)

func main() {
	name := "example"
	logPath := fmt.Sprintf("./runtime/logs/%s.log", filepath.Base(os.Args[0]))

	logger := v1log.NewZapLog(name, logPath, nil)
	httpServer, err := v1http.NewHttpServer("", ":28080")
	if err != nil {
		logger.Error("run http server error:%s" + err.Error())
		return
	}
	//添加logger
	httpServer.AddLogger(logger)

	api := &ApiHandler{}

	//注册简单的路由
	httpServer.RouteGet("/v1", api.Index, nil)

	//使用json返回
	httpForward := v1http.NewHttpForwardHandler("127.0.0.1:8080/v1/users", time.Second)
	httpForward.AddForwardRule(map[string]string{
		"/v2/users/*": "127.0.0.1:28080/v1/users",
		"/v2/self":       "127.0.0.1:28080/v1",
		"/v2/file/*/index.html":      "127.0.0.1:8080/static",
	})

	httpServer.RouteHandler("GET", "/v1/users/:uid", httpForward, []v1http.Middleware{
		ForwardMiddleware,
	})
	httpServer.RouteHandler("GET", "/v2/*path", httpForward, []v1http.Middleware{
		ForwardMiddleware,
	})

	logger.Fatal(httpServer.Run().Error())
}

type ApiHandler struct {
}

//http router
func (h *ApiHandler) Index(ctx *v1http.Ctx) {
	ctx.Write([]byte("Hello World"))
}

//中间件中设置 自定义response处理器
var ForwardMiddleware v1http.Middleware = func(ctx *v1http.Ctx, next func(*v1http.Ctx)) {
	next(ctx)
	ctx.Write([]byte("\nforward: " + ctx.Param("uid")))
}
